<template>
	<view>
		<uni-search-bar v-model="searchKeyword" @input="handleSearch" @clear="handleSearch" placeholder="请输入物品名称"
			radius="5"></uni-search-bar>
		<cy-cate ref="cyCate" :categories="categories" :active-category-id="selectedCategoryId"
			:goods-list="currentCategoryGoods || []" :showcart="false" :showplus="false" @goodsclick="handleGoodClick"
			@submit="btn_click" @category-click="handleCategoryClick" />

		<!-- 新增按钮 -->
		<uni-fab ref="fab" horizontal="right" vertical="bottom" @fabClick="fabClick" />

		<!-- 加载更多提示 -->
		<view v-if="loadingMore" class="loading-more">
			<text>加载中...</text>
		</view>
		<view v-if="!hasMore && currentCategoryGoods.length > 0" class="no-more">
			<text>没有更多数据了</text>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				searchKeyword: '',
				categories: [],
				selectedCategoryId: '',
				goodsMapAll: {}, // 所有商品缓存
				loadedCategories: [], // 已加载的分类ID列表
				loading: false, // 页面初始加载状态
				loadingMore: false, // 上拉加载更多状态
				pageNum: 1,
				pageSize: 10,
				hasMore: true // 是否还有更多数据
			}
		},
		onLoad() {
			this.loadCategories()
		},
		onPullDownRefresh() {
			// 下拉刷新
			this.resetAndReload()
			uni.stopPullDownRefresh()
		},
		onReachBottom() {
			// 上拉加载更多
			if (this.hasMore && !this.loading && !this.loadingMore) {
				this.loadMoreGoods()
			}
		},
		computed: {
			currentCategoryGoods() {
				const goodsArray = Object.values(this.goodsMapAll || {})
				if (!Array.isArray(goodsArray)) return []
				return goodsArray.filter(goods => goods && goods.category_id === this.selectedCategoryId)
			}
		},
		methods: {
			async loadCategories() {
				try {
					const obj = uniCloud.importObject('goods')
					const res = await obj.getCategoriesList({})

					if (res.code === 0) {
						this.categories = res.data.map(item => ({
							_id: item._id,
							name: item.name
						}))

						if (this.categories.length > 0) {
							this.selectedCategoryId = this.categories[0]._id
							this.resetAndReload()
						}
					}
				} catch (error) {
					uni.showToast({
						title: '获取分类失败',
						icon: 'none'
					})
				}
			},

			async resetAndReload() {
				this.pageNum = 1
				this.hasMore = true
				this.goodsMapAll = {}
				this.loadedCategories = []
				await this.loadGoodsList()
			},

			async loadGoodsList(refresh = false) {
				if (!this.selectedCategoryId || (this.loadedCategories.includes(this.selectedCategoryId) && !
					refresh)) {
					return
				}

				this.loading = true
				if (refresh) {
					this.pageNum = 1
					this.hasMore = true
				}

				try {
					const queryCondition = {
						category_id: this.selectedCategoryId
					}

					if (this.searchKeyword.trim()) {
						queryCondition.name = {
							$regex: this.searchKeyword,
							$options: 'i'
						}
					}

					const obj = uniCloud.importObject('goods')
					const res = await obj.getGoods({
						queryCondition,
						pageNum: this.pageNum,
						pageSize: this.pageSize
					})

					if (res.code === 0) {
						const newGoodsMap = refresh ? {} : {
							...this.goodsMapAll
						}

						res.data.forEach(goods => {
							const existing = newGoodsMap[goods._id]
							newGoodsMap[goods._id] = {
								...goods,
								_cartNumber: existing ? existing._cartNumber : 0
							}
						})

						this.goodsMapAll = newGoodsMap

						if (res.data.length < this.pageSize) {
							this.hasMore = false
						}

						if (!this.loadedCategories.includes(this.selectedCategoryId)) {
							this.loadedCategories.push(this.selectedCategoryId)
						}
					}
				} catch (error) {
					uni.showToast({
						title: '获取商品失败',
						icon: 'none'
					})
				} finally {
					this.loading = false
				}
			},

			async loadMoreGoods() {
				if (!this.selectedCategoryId || !this.hasMore || this.loading || this.loadingMore) {
					return
				}

				this.loadingMore = true
				try {
					const queryCondition = {
						category_id: this.selectedCategoryId
					}

					if (this.searchKeyword.trim()) {
						queryCondition.name = {
							$regex: this.searchKeyword,
							$options: 'i'
						}
					}

					const obj = uniCloud.importObject('goods')
					const res = await obj.getGoods({
						queryCondition,
						pageNum: this.pageNum + 1,
						pageSize: this.pageSize
					})

					if (res.code === 0) {
						if (res.data.length < this.pageSize) {
							this.hasMore = false
						}

						const newGoodsMap = {
							...this.goodsMapAll
						}
						res.data.forEach(goods => {
							const existing = newGoodsMap[goods._id]
							newGoodsMap[goods._id] = {
								...goods,
								_cartNumber: existing ? existing._cartNumber : 0
							}
						})

						this.goodsMapAll = newGoodsMap
						this.pageNum++
					}
				} catch (error) {
					uni.showToast({
						title: '加载更多失败',
						icon: 'none'
					})
				} finally {
					this.loadingMore = false
				}
			},

			handleCategoryClick(category) {
				this.selectedCategoryId = category._id
				this.resetAndReload()
			},

			handleGoodClick(goods) {
				uni.$router.to({
					url: '/pagesB/item/detail',
					params: {
						goods
					}
				})
			},

			handleSearch() {
				this.resetAndReload()
			},

			fabClick() {
				uni.$router.to({
					url: '/pagesA/item/goods/add'
				})
			},

			async update_remaincount(item) {
				try {
					item.remain_count = Number(item.remain_count)
					const obj = uniCloud.importObject('goods')
					const res = await obj.batchUpdateGoods(item)

					if (res.code === 0) {
						uni.showToast({
							title: '更新成功',
							icon: 'success',
							duration: 1000
						})

						setTimeout(() => {
							this.loadGoodsList()
							uni.hideLoading()
						}, 2000)
					} else {
						uni.showToast({
							title: `更新失败：${res.message}`,
							icon: 'none',
							duration: 3000
						})
					}
				} catch (e) {
					uni.showToast({
						title: '网络异常，请稍后重试',
						icon: 'none'
					})
				}
			},

			async btn_click(item) {
				try {
					const userinfo = uni.getStorageSync('userInfo')
					if (!userinfo?._id) {
						uni.showToast({
							title: '请先登录',
							icon: 'error'
						})
						return
					}

					if (item.length === 0) {
						uni.showToast({
							title: '请先选择物品',
							icon: 'error'
						})
						return
					}

					const now = uni.$dayjs(new Date()).format('YYYYMMDD')
					const randomNum = Math.floor(Math.random() * 900000) + 100000
					const userSuffix = userinfo._id.slice(-4)
					const order_id = `${now}-${randomNum}-${userSuffix}`

					const goodsRecord = {
						order_id,
						create_date: uni.$dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss'),
						user_id: userinfo._id,
						user_name: userinfo.username,
						goods: item,
						status: 0
					}

					const obj = uniCloud.importObject('goods')
					const res = await obj.addGoodsRecord(goodsRecord)

					const toastConfig = res.code === 0 ? {
						icon: 'success',
						title: res.message
					} : {
						icon: 'none',
						title: res.message
					}
					uni.showToast(toastConfig)

					if (res.code === 0) {
						await this.update_remaincount(item)
					}
				} catch (error) {
					uni.showToast({
						icon: 'error',
						title: '请求失败，请检查网络'
					})
				}
			}
		}
	}
</script>

<style>
	.loading-more,
	.no-more {
		text-align: center;
		padding: 20rpx 0;
		color: #999;
		font-size: 28rpx;
	}
</style>